/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUI.java
 *
 * Created on 29/06/2012, 01:42:57 PM
 */
package SudokuGenetico;

import SudokuGenetico.jgap.JGAPSudoku;
import SudokuGenetico.watchmaker.WatchmakerSudoku;
import herramientas.Timing;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import rutas.GetRoutes;

/**
 *
 * @author civilian
 */
public class GUI extends javax.swing.JFrame {

    private boolean tomarTiempos = false;

    /** Creates new form GUI */
    public GUI() {
        super("Solucion Sudoku Implementado Con Paquetes de Algoritmos Geneticos");
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        textArea2 = new java.awt.TextArea();
        textArea1 = new java.awt.TextArea();
        sPoblacion = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        sGeneraciones = new javax.swing.JSpinner();
        bSolucionar = new javax.swing.JButton();
        taWatchmaker = new java.awt.TextArea();
        taJpag = new java.awt.TextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        sPoblacion.setValue(100);

        jLabel1.setText("Poblacion");

        jLabel2.setText("Generaciones");

        sGeneraciones.setValue(60);

        bSolucionar.setText("Solucionar");
        bSolucionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSolucionarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bSolucionar)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(sPoblacion, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(taJpag, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(sGeneraciones, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(taWatchmaker, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {bSolucionar, jLabel1, jLabel2, sGeneraciones, sPoblacion});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(sPoblacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bSolucionar))
                    .addComponent(jLabel2)
                    .addComponent(sGeneraciones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(taWatchmaker, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                    .addComponent(taJpag, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {bSolucionar, jLabel1, jLabel2});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {sGeneraciones, sPoblacion});

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void bSolucionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSolucionarActionPerformed

    try {
        if ((Integer) sPoblacion.getValue() < 1 || (Integer) sGeneraciones.getValue() < 1) {
            JOptionPane.showMessageDialog(this, "Poblaciones o generaciones menores que 1 fuera del entendimiento de los programadores\n"
                    + "Por favor digitelas correctamente, Gracias :)");
            int genera = (Integer) sGeneraciones.getValue();
            int pobla = (Integer) sPoblacion.getValue();
            genera = Math.abs((genera * (-1)) + 1);
            pobla = Math.abs((pobla * (-1)) + 1);

            if (genera + pobla == 1) {
                JOptionPane.showMessageDialog(this, "Sip es un ciclo infinito xD, felicitaciones por encontrarlo");
            }

            sGeneraciones.setValue(genera);
            sPoblacion.setValue(pobla);

            return;
        }

        String archivo = GetRoutes.escogerRutaArchivo();
        tomarTiempos = false;
        if (tomarTiempos) {//no tener en cuenta este if para el entendimiento de el problema solo se utiliza para generar datos de prueba
            // <editor-fold defaultstate="collapsed" desc="Codigo de tomar tiempos">
            int poblacion = 1000;
            int generaciones = 60;
            taJpag.append("Poblacion = " + poblacion + " Generaciones = " + generaciones + "\n");
            taJpag.append(String.format("%s\t %s\t %s\t \n", "poblacion", "jgap", "watchmaker"));
            String jpa = "";
            String watch = "";
            for (int i = 0; i < 1100; i += 100) {
                Timing t = new Timing();
                t.tomarTiempo();
                JGAPSudoku sud;
                sud = new JGAPSudoku(null, archivo, poblacion + i, generaciones);
                sud.solveSudoku();
                jpa = t.tomarTiempo();
                WatchmakerSudoku o = new WatchmakerSudoku(null, archivo, poblacion + i, generaciones);
                o.solveSudoku();
                watch = t.tomarTiempo();
                taJpag.append(String.format("%s\t %s\t %s\t \n", poblacion + i, jpa, watch));
            }
            return;
        }// </editor-fold>//IF

        JGAPSudoku sud;
        sud = new JGAPSudoku(taJpag, archivo, (Integer) sPoblacion.getValue(), (Integer) sGeneraciones.getValue());
        sud.solveSudoku();
        WatchmakerSudoku o = new WatchmakerSudoku(taWatchmaker, archivo, (Integer) sPoblacion.getValue(), (Integer) sGeneraciones.getValue());
        o.solveSudoku();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}//GEN-LAST:event_bSolucionarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new GUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bSolucionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSpinner sGeneraciones;
    private javax.swing.JSpinner sPoblacion;
    private java.awt.TextArea taJpag;
    private java.awt.TextArea taWatchmaker;
    private java.awt.TextArea textArea1;
    private java.awt.TextArea textArea2;
    // End of variables declaration//GEN-END:variables
}
